<?php

class LoginModel extends Model
{
	public function __construct()
	{
		parent::__construct();
		
		if (Input::request("action") != "login") return;
		
		$playerName = Input::request("name");
		$pass = Input::request("password");
		
		if (!preg_match(PATTERN_PLAYER_NAME, $playerName))
			$this->addError("name", "PLAYER_NAME_ERROR");
		$passLen = strlen($pass);
		if ($passLen < 3 || $passLen > 16)
			$this->addError("password", "PASSWORD_ERROR");
			
		if (!$this->hasError())
		{
			$player = PlayerRegistry::i()->byName($playerName);
			if (is_null($player) || !$player->testPass($pass))
				$this->addError("auth", "INVALID_LOGIN_PASSWORD");
			else
			{
				Session::set("auth", array("player_id" => $player->id(), "ac_level" => $player->acLevel()));
				if (Input::hasRequest("redirect"))
				{
					header("Location: /?action=login&view=" . Input::request("redirect"));
					die();
				}
				header("Location: /?view=city&action=login");
				die();
			}
		}
	}
}

?>